package com.zbbt.sportslottery.ui.fragment;

import java.util.ArrayList;
import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.gc.materialdesign.views.ButtonRectangle;
import com.gc.materialdesign.views.ProgressBarCircularIndetermininate;
import com.google.gson.JsonObject;
import com.zbbt.sportslottery.R;
import com.zbbt.sportslottery.app.App;
import com.zbbt.sportslottery.app.Constant;
import com.zbbt.sportslottery.app.ServerConfig;
import com.zbbt.sportslottery.bean.FindingNewsInformation;
import com.zbbt.sportslottery.bean.SuperResult;
import com.zbbt.sportslottery.db.DbManager;
import com.zbbt.sportslottery.net.TypeGsonHttpHandler;
import com.zbbt.sportslottery.net.ZbHttpClient;
import com.zbbt.sportslottery.ui.adapter.FindingAdapter;
import com.zbbt.sportslottery.ui.adapter.FindingAdapter.OnBottomClickListener;
import com.zbbt.sportslottery.ui.widget.swipe.SwipeRefreshLayout;
import com.zbbt.sportslottery.ui.widget.swipe.SwipeRefreshLayout.OnRefreshListener;
import com.zbbt.sportslottery.util.LogUtil;
import com.zbbt.sportslottery.util.ToastUtil;

public class FindingFragment extends BaseMenuFragment {

	private FindingAdapter findAdapter;
	private List<FindingNewsInformation> homeListData = new ArrayList<FindingNewsInformation>();// 列表数据
	private ListView findList;
	private SwipeRefreshLayout mSwipeRefreshLayout;
	private int pageTotal = 0;// 读取本地缓存翻页 当前页数
	private int thisPageSize = 10;// 读取本地缓存翻页 一页10条
	private int whatpage = 1;
	private int page_size = 10;
	private boolean hasmore_data = true;// 是否有下一页数据
	private boolean sethttp = true;// 二次请求
	private ProgressBarCircularIndetermininate progressBar;
	// private boolean isfirst = true;// 如果是第一次进来 请求完数据后延时2秒再刷新下界面
	private LinearLayout error_layout;// 无网络时 显示的界面
	private boolean isError = false;
	private ButtonRectangle buttonRectangle;
	private View bottomView;
	private TextView bottom_tx;

	public static FindingFragment getInstance() {
		return new FindingFragment();
	}

	@Override
	protected void initView(LayoutInflater inflater) {
		mView = inflater.inflate(R.layout.fragment_finding, null);
		error_layout = (LinearLayout) findViewById(R.id.error_layout);
		error_layout.setVisibility(View.GONE);
		progressBar = (ProgressBarCircularIndetermininate) findViewById(R.id.progressBarCircularIndetermininate);
		findList = (ListView) findViewById(R.id.finding_list);
		bottomView = inflater.inflate(R.layout.fragment_bottom_layout, null);
		bottom_tx = (TextView) bottomView.findViewById(R.id.bottom_tx);
		bottomView.setVisibility(View.GONE);
		findList.addFooterView(bottomView);
		if (findAdapter == null) {
			findAdapter = new FindingAdapter(homeListData, getActivity());
			findAdapter.setOnBottomClickListener(new OnBottomClickListener() {
				@Override
				public void onBottomClick() {
					bottomView.setVisibility(View.VISIBLE);
					if (hasmore_data) {
						if (sethttp == true) {
							getHomeListData(Constant.HAS_MORE);
						}
					} else {
						bottom_tx.setText("暂无更多数据");
					}
				}
			});
		}
		findList.setAdapter(findAdapter);
		mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.finding_swipe_container);
		mSwipeRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
			@Override
			public void onRefresh() {
				if (sethttp) {
					hasmore_data = true;
					getHomeListData(Constant.REFRESH);
				}
			}
		});
		getHomeListData(Constant.REFRESH);
		findList.setBackgroundResource(R.color.gray_bg);
	}

	private void getHomeListData(final int method) {
		sethttp = false;
		mSwipeRefreshLayout.setRefreshing(true);
		if (method == Constant.REFRESH) {
			this.whatpage = 1;
		}
		JsonObject jsonObject = new JsonObject();
		// jsonObject.addProperty("category_id",
		// Constant.CATEGORY_IDS_FAXIAN[1]);
		// LogUtil.printE("ConsultAllFragment", "name=" +
		// Constant.CATEGORY_IDS_FAXIAN[1]);
		jsonObject.addProperty("pageSize", page_size);
		jsonObject.addProperty("curPage", whatpage);
		jsonObject.addProperty("findType", 1);
		ZbHttpClient.postNewApi(ServerConfig.API_FINDING, jsonObject, new TypeGsonHttpHandler<SuperResult<FindingNewsInformation>>(false) {
			@Override
			public void onSuccess(SuperResult<FindingNewsInformation> data) {
				mSwipeRefreshLayout.setRefreshing(false);
				if (method == Constant.REFRESH) {
					homeListData.clear();
					homeListData.addAll(data.getData());
					if (data.getTotalPage() == 1) {
						bottom_tx.setText("暂无更多数据");
					}
				} else if (method == Constant.HAS_MORE) {
					if (data.getData() != null && data.getData().size() > 0) {
						homeListData.addAll(data.getData());
					}
					if (data.getTotalPage() > data.getCurPage()) {
						hasmore_data = true;
					} else {
						hasmore_data = false;
						bottom_tx.setText("暂无更多数据");
					}
				}
				whatpage++;
				findAdapter.notifyDataSetChanged();
				progressBar.setVisibility(View.GONE);
				DbManager.saveFindList(homeListData);
				sethttp = true;
				error_layout.setVisibility(View.GONE);
			}

			@Override
			public void onFailure(String errorCode, String errorMsg) {
				LogUtil.printD("ConsultAllFragment", "失败" + errorMsg);
				mSwipeRefreshLayout.setRefreshing(false);
				progressBar.setVisibility(View.GONE);
				sethttp = true;
				if (method == Constant.HAS_MORE) {
					pageTotal++;
					getHomeLocalList();
				} else {
					pageTotal = 0;
					homeListData.clear();
					getHomeLocalList();
				}
			}
		});
	}

	/**
	 * 获取首页列表本地缓存数据
	 */
	public void getHomeLocalList() {
		List<FindingNewsInformation> listdata = DbManager.getFindList(thisPageSize, pageTotal);
		if (listdata != null) {
			if (listdata.size() > 0) {
				homeListData.addAll(listdata);
				findAdapter.notifyDataSetChanged();
			} else {
				hasmore_data = false;
			}
		} else {
			error_layout.setVisibility(View.VISIBLE);
		}

	}

	@Override
	protected void setListener() {
//		error_layout.setOnClickListener(this);
	}

	@Override
	protected void onClickEvent(View v) {
//		switch (v.getId()) {
//		case R.id.error_layout:
//			getHomeListData(Constant.REFRESH);
//			progressBar.setVisibility(View.VISIBLE);
//			break;
//		default:
//			break;
//		}

	}

	@Override
	protected void initData() {
		// TODO Auto-generated method stub
		IntentFilter filter = new IntentFilter();
		filter.addAction(Constant.INTENT_ACTION_CHANGE_CITY);
		context.registerReceiver(broadcastReceiver, filter);
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if (Constant.isShowStatic == true) {
			if (findAdapter != null) {
				findAdapter.notifyDataSetChanged();
			}
		}
	}

	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}

	/**
	 * 注册的广播
	 */
	private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			if (Constant.INTENT_ACTION_CHANGE_CITY.equals(intent.getAction())) {
				hasmore_data = true;
				getHomeListData(Constant.REFRESH);
			}
		}

	};

}
